/**
 * @create 2022-05-02
 * @desc 优化判断条件：通过 generate 临时编译编码进行判断
 */

const {getBaseData} = require('../utils/index')

const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const generate = require('@babel/generator').default;
const types = require('@babel/types');

const {sourceCode, outputFn} = getBaseData();

const ast = parser.parse(sourceCode, {
    sourceType: 'unambiguous',
    plugins: ['jsx']
});

traverse(ast, {
    CallExpression(path, state) {
        const {node} = path;
        const calleeNames = ['log', 'error', 'warn', 'info'].map(name => `console.${name}`);
        const calleeCode = generate(node.callee).code;
        if (calleeNames.includes(calleeCode)) {
            const {line, column} = node.callee.loc.start;
            node.arguments.unshift(types.stringLiteral(`[info]: line: ${line}, column: ${column} \n: `))
        }
    }
});

const { code, map } = generate(ast);
outputFn(code)